<template>
  <div>
    <el-upload class="upload-demo"
               action="actionUrl"
               :on-change="handleChange"
               :show-file-list="false"
               :data="addDemandId"
               :on-success="successadd"
               :headers="myHeaders"
               :http-request="uploadImage">
      <el-button size="small"
                 type="primary"
                 v-if="page=='demand'">点击上传</el-button>
    </el-upload>

    <el-table :data="fileList"
              border
              style="width: 100%">
      <el-table-column prop="demandId"
                       property="demandId"
                       label="需求id"
                       width="50px"
                       v-if="false"></el-table-column>
      <el-table-column prop="fileName"
                       property="fileName"
                       label="附件名"
                       style="width: 100%">
        <template slot-scope="scope">
          <el-popover trigger="hover"
                      placement="top">
            <p>上传时间: {{ scope.row.createTime }}</p>
            <div slot="reference"
                 class="name-wrapper">
              {{ scope.row.fileName }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="fileAddress"
                       property="fileAddress"
                       label="需求id"
                       width="50"
                       v-if="false">
      </el-table-column>
      <el-table-column label="操作"
                       width="95px"
                       align="center">
        <template slot-scope="scope">

          <el-upload style="float: left;"
                     class="upload-demo"
                     action="/apis/demand/uploadFile"
                     :on-change="handleChange"
                     :show-file-list="false"
                     :data="addDemandId"
                     v-if="page=='demand'"
                     :on-success="successupdate"
                     :headers="myHeaders"
                     ref="upload">
            <!-- <el-button style="float: left; margin-right: 10px;" size="small"  v-if="page=='demand'" @click="replace(scope.row)" >替换</el-button> -->
          </el-upload>
          <!-- <el-button @click="open(scope.row)" size="small">直接打开</el-button> -->
          <!--  <el-button @click="replace(scope.row)" size="small" v-if="page=='demand'">替换</el-button> -->

          <el-button @click="download(scope.row)"
                     type="text">下载</el-button>
          <el-button @click="handleDelete(scope.row)"
                     type="text"
                     v-if="page=='demand'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 删除提示框 -->

    <el-dialog title="提示"
               :visible.sync="delVisible"
               width="300px"
               center
               append-to-body>

      <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>

      <span slot="footer"
            class="dialog-footer">

        <el-button @click="delVisible = false">取 消</el-button>

        <el-button type="primary"
                   @click="deletefj()">确 定</el-button>

      </span>

    </el-dialog>
  </div>
</template>

<script>
import { downFile, uploadFile } from '@/api/uaDemandPool';
import { delFile } from '@/api/uaDemand';
import { getStore } from '@/router/mUtils'
import { Message } from "element-ui";
export default {
  props: {
    demandId: {  //需求id
      type: String,
      default: ''
    },
    page: {
      type: String,
      default: ''

    },
    fileList: {
      type: Array,
      default: () => []
    },
  },
  data () {
    return {
      actionUrl: '/apis/demand/uploadFile',
      addDemandId: {
        id: '',
        fileId: '',
      },
      fjid: '',
      myHeaders: {
        token: '',
      },
      delVisible: false,
      msg: "",//记录每一条的信息，便于取id
      delarr: "",//存放删除的数据
      idx: '',
      data: '',
    }
  },
  created () {
    let userInfo = getStore('userInfo');
    this.myHeaders.token = JSON.parse(userInfo).token;
  },
  methods: {
    uploadImage (param) {
      const formData = new FormData()
      formData.append('file', param.file)
      formData.append('id', this.demandId)
      uploadFile(formData).then(response => {
        if (response.data.code == '000000') {
          this.$emit("refreshData");
          Message.success("附件添加成功")
        } else {
          Message.error(response.data.message)
        }

      })
    },

    // 下载
    download (val) {
      //window.location.href=val.fileAddress;
      downFile({ fileId: val.id }).then(res => {
        var blob = new Blob([res.data], { type: 'application/octet-stream;charset=UTF-8' });
        var contentDisposition = res.headers['content-disposition'];
        var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*');
        var result = patt.exec(contentDisposition);
        //对文件名乱码转义--【Node.js】使用iconv-lite解决中文乱码
        let iconv = require("iconv-lite");
        iconv.skipDecodeWarning = true;//忽略警告
        let filename = iconv.decode(result[1], "utf-8");
        var downloadElement = document.createElement('a');
        var href = window.URL.createObjectURL(blob); // 创建下载的链接
        var reg = /^["](.*)["]$/g;
        downloadElement.style.display = 'none';
        downloadElement.href = href;
        downloadElement.download = decodeURI(filename.replace(reg, '$1')); // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click(); // 点击下载
        document.body.removeChild(downloadElement); // 下载完成移除元素
        window.URL.revokeObjectURL(href);
      })
    },
    replace (val) {
      this.fjid = val.id;
      this.$refs.upload.submit();
    },
    // 文件上传
    handleChange (file, fileList) {
      // this.addDemandId.id=this.fileList[0].demandId;
      this.addDemandId.id = this.demandId
      this.addDemandId.fileId = this.fjid;
    },
    successadd (response, file, fileList) {
      if (response.code == "000000") {
        this.$emit("refreshData");
        Message.success("附件添加成功");
      } else {
        Message.error(response.message);
      }
    },
    successupdate (response, file, fileList) {
      if (response.code == "000000") {
        this.$emit("refreshData");
        Message.success("附件替换成功");
      } else {
        Message.error(response.message);
      }
    },
    // 存放删除的信息
    handleDelete (row) {

      this.msg = row;//要删除的信息

      this.delarr = this.msg.id;

      this.delVisible = true;
    },
    deletefj () {
      delFile({ fileId: this.delarr }).then(res => {
        if (res.data != null && res.data.code == "000000") {
          this.delVisible = false
          this.$emit("refreshData");
          Message.success("附件删除成功");
        } else {
          Message.error(response.message);
        }
      });
    }
  },


}
</script>

<style>
</style>
